package com.duofan.gmall.ware.config;

import com.duofan.gmall.common.utils.MyRabbitUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class MyRabbitConfig {

    public static final String STOCK_EVENT_EXCHANGE = "stock-event-exchange";
    public static final String STOCK_RELEASE_STOCK_QUEUE = "stock.release.stock.queue";
    public static final String STOCK_DELAY_QUEUE = "stock.delay.queue";
    public static final String STOCK_LOCKED_ROUTING_KEY = "stock.locked ";
    public static final String STOCK_RELEASE_ROUTING_KEY ="stock.release.#";

    public static final String DEAD_LETTER_ROUTING_KEY = "stock.release";
    // 库存解锁时间设为40分钟
    public static final int MESSAGE_TTL = 40*60*1000;


    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public Exchange stockEventExchange() {
        TopicExchange exchange = new TopicExchange(STOCK_EVENT_EXCHANGE, true, false);
        return exchange;
    }

    @Bean
    public Queue stockReleaseStockQueue() {
        Queue queue = new Queue(STOCK_RELEASE_STOCK_QUEUE, true, false, false);
        return queue;
    }

    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> args = MyRabbitUtils.buildDeadLetterArgs(STOCK_EVENT_EXCHANGE, DEAD_LETTER_ROUTING_KEY, MESSAGE_TTL);
        Queue queue = new Queue(STOCK_DELAY_QUEUE, true, false, false, args);
        return queue;
    }

    @Bean
    public Binding stockReleaseBinding() {
        Binding binding = new Binding(STOCK_RELEASE_STOCK_QUEUE, Binding.DestinationType.QUEUE,
                STOCK_EVENT_EXCHANGE, STOCK_RELEASE_ROUTING_KEY, null);
        return binding;
    }

    @Bean
    public Binding stockLockedBinding() {
        Binding binding = new Binding(STOCK_DELAY_QUEUE, Binding.DestinationType.QUEUE,
                STOCK_EVENT_EXCHANGE, STOCK_LOCKED_ROUTING_KEY, null);
        return binding;
    }

    @Bean
    ApplicationRunner runner(ConnectionFactory cf) {
        return args -> cf.createConnection().close();
    }

}
